package ru.agiledev.akb.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import ru.agiledev.akb.client.AuthorizationService;
import ru.agiledev.akb.server.domain.presentation.Author;
import ru.agiledev.akb.server.util.AuthenticationManager;
import ru.agiledev.akb.shared.User;

import javax.servlet.http.HttpSession;

/**
 * Created by a.kirillov
 * Date: 4/3/11 Time: 11:09 AM
 */
public class AuthorizationServiceImpl extends RemoteServiceServlet implements AuthorizationService{


    private static final String USER_SESSION = "AKBApplicationUser";

	private static final long serialVersionUID = 1;

	private void setUserInSession(User user) {
		HttpSession session = getThreadLocalRequest().getSession();
		session.setAttribute(USER_SESSION, user);
	}

	private User getUserFromSession() {
		HttpSession session = getThreadLocalRequest().getSession();
		return (User) session.getAttribute(USER_SESSION);
	}

    @Override
	public User checkLogin(String userName, String password) {
        Author author = AuthenticationManager.authenticateUser(userName, password);

        if(author!=null){
            return author.getUserView();
        }
		return null;
	}

    @Override
	public void logout() {
		HttpSession session = getThreadLocalRequest().getSession();
		if (session != null)
			session.invalidate();

	}

    @Override
	public User isSessionAlive() {
		/*User bean = getUserFromSession();
		if ((bean != null) && (bean.getUserName().length() != 0)) {
			System.out.println("User " + bean.getUserName()
					+ " is already logged in");
			return bean;
		}*/
		return null;
	}

	@Override
	public User getUser(Long id) {
		/*Iterator i = getUserList().iterator();
		while (i.hasNext()) {
			User user = (User) i.next();
			if (user.getId().equals(id))
				return user;
		}*/
		return null;
	}

}
